package com.sky.gateway.filters;

import com.sky.constant.JwtClaimsConstant;
import com.sky.gateway.config.AuthProperties;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@RequiredArgsConstructor
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class UserFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtProperties jwtProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        if(isExclude(path.toString())){
            return chain.filter(exchange);
        }
        //1、从请求头中获取令牌
        List<String> tokens = request.getHeaders().get(jwtProperties.getUserTokenName());
        Long userId = null;
        //2、校验令牌
        try {
            log.info("jwt校验:{}", tokens.get(0));
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), tokens.get(0));
            userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id：{}", userId);

//             将当前登陆用户的id存入ThreadLocal
//            BaseContext.setCurrentId(userId);


        } catch (Exception ex) {
            //4、不通过，响应401状态码
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        Long finalUserId = userId;
        ServerWebExchange serverWebExchange = exchange.mutate().request(builder -> builder.header("user-info", finalUserId.toString())).build();
        //3、通过，放行
        return chain.filter(serverWebExchange);
    }
    public boolean isExclude(String path){
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,path))return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
